import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { FileText, Search } from "lucide-react";
import { useState } from "react";
import { UnifiedCard } from "./UnifiedCard";

const templates = [
  {
    id: "1",
    title: "Lab Report Template",
    description: "Complete template for scientific lab reports with hypothesis, methodology, results, and conclusion sections",
    category: "Lab Reports",
    tags: ["Science", "Lab Report", "Research"],
    downloads: 2456,
    canEdit: true,
    isOnlineWritable: true,
    popularity: 2456
  },
  {
    id: "2",
    title: "Research Proposal Format",
    description: "Professional research proposal template with literature review, methodology, and timeline sections",
    category: "Research Proposals",
    tags: ["Research", "Proposal", "Academic"],
    downloads: 1893,
    canEdit: true,
    isOnlineWritable: true,
    popularity: 1893
  },
  {
    id: "3",
    title: "Presentation Slides Template",
    description: "Clean, academic presentation template with title slides, content layouts, and reference sections",
    category: "Presentations",
    tags: ["Presentation", "Slides", "Visual"],
    downloads: 3241,
    canEdit: false,
    isOnlineWritable: false,
    popularity: 3241
  },
  {
    id: "4",
    title: "Essay Structure Guide",
    description: "Five-paragraph essay template with introduction, body paragraphs, and conclusion frameworks",
    category: "Essays & Reflections",
    tags: ["Essay", "Writing", "Structure"],
    downloads: 4567,
    canEdit: true,
    isOnlineWritable: true,
    popularity: 4567
  },
  {
    id: "5",
    title: "Group Project Planner",
    description: "Collaborative template for planning group assignments with task distribution and timeline management",
    category: "Group Projects",
    tags: ["Group Work", "Planning", "Collaboration"],
    downloads: 1234,
    canEdit: true,
    isOnlineWritable: true,
    popularity: 1234
  },
  {
    id: "6",
    title: "Creative Portfolio Layout",
    description: "Showcase your creative work with this professional portfolio template design",
    category: "Creative Work",
    tags: ["Creative", "Portfolio", "Design"],
    downloads: 892,
    canEdit: false,
    isOnlineWritable: false,
    popularity: 892
  }
];

const filterCategories = [
  { id: "all", label: "All Templates" },
  { id: "lab-reports", label: "Lab Reports" },
  { id: "research-proposals", label: "Research Proposals" },
  { id: "essays-reflections", label: "Essays & Reflections" },
  { id: "presentations", label: "Presentations" },
  { id: "creative-work", label: "Creative Work" },
  { id: "group-projects", label: "Group Projects" }
];

export function AssignmentTemplates() {
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [showOnlineWritableOnly, setShowOnlineWritableOnly] = useState(false);
  const [sortBy, setSortBy] = useState("popular");

  const filteredTemplates = templates.filter(template => {
    // Search filter
    const matchesSearch = searchQuery === "" || 
      template.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      template.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      template.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()));

    // Category filter
    const matchesCategory = selectedCategory === "all" || 
      (() => {
        const categoryMap: { [key: string]: string } = {
          "lab-reports": "Lab Reports",
          "research-proposals": "Research Proposals",
          "essays-reflections": "Essays & Reflections",
          "presentations": "Presentations",
          "group-projects": "Group Projects",
          "creative-work": "Creative Work"
        };
        return categoryMap[selectedCategory] === template.category;
      })();

    // Online writable filter
    const matchesOnlineWritable = !showOnlineWritableOnly || template.isOnlineWritable;

    return matchesSearch && matchesCategory && matchesOnlineWritable;
  }).sort((a, b) => {
    switch (sortBy) {
      case "popular":
        return b.popularity - a.popularity;
      case "recent":
        return 0; // Would use actual dates in real implementation
      case "recommended":
        return 0; // Would use recommendation algorithm in real implementation
      default:
        return 0;
    }
  });

  const handleCategoryFilter = (categoryId: string) => {
    setSelectedCategory(categoryId);
  };

  const handleStartWriting = (templateTitle: string) => {
    console.log(`Starting online writing for: ${templateTitle}`);
    // Mirror Agent integration would trigger here
  };

  const handleDownload = (templateTitle: string) => {
    console.log(`Downloading template: ${templateTitle}`);
  };

  return (
    <div className="space-y-6">
      {/* Subtitle */}
      <div className="text-center">
        <p className="text-gray-600 text-sm">
          Professional templates for lab reports, essays, presentations, and research proposals
        </p>
      </div>

      {/* Sticky Filter Bar */}
      <div className="sticky top-0 bg-white z-10 pb-4 border-b border-gray-100">
        <div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
          {/* Search */}
          <div className="relative w-full lg:w-80">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="Search templates..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>

          {/* Sort */}
          <Select value={sortBy} onValueChange={setSortBy}>
            <SelectTrigger className="w-full lg:w-48">
              <SelectValue placeholder="Sort by" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="popular">Most Popular</SelectItem>
              <SelectItem value="recent">Recently Added</SelectItem>
              <SelectItem value="recommended">Recommended for Me</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* Category Filter Pills */}
        <div className="flex items-center gap-2 flex-wrap mt-4">
          {filterCategories.map((category) => (
            <Button
              key={category.id}
              variant={selectedCategory === category.id ? "default" : "outline"}
              size="sm"
              onClick={() => handleCategoryFilter(category.id)}
              className={`${
                selectedCategory === category.id 
                  ? "bg-gray-900 text-white hover:bg-gray-800" 
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200 border-gray-300"
              } rounded-full px-4 py-2`}
            >
              {category.label}
            </Button>
          ))}
        </div>

        {/* Online Writable Toggle */}
        <div className="flex items-center gap-3 mt-3">
          <Switch
            id="online-writable"
            checked={showOnlineWritableOnly}
            onCheckedChange={setShowOnlineWritableOnly}
          />
          <label htmlFor="online-writable" className="text-sm text-gray-600">
            Show Online-Writable Templates Only
          </label>
        </div>
      </div>

      {/* Statistics */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-600">
          Found {filteredTemplates.length} templates
        </p>
        <Badge variant="secondary" className="bg-indigo-100 text-indigo-700">
          Total Downloads: {templates.reduce((sum, template) => sum + template.downloads, 0)}
        </Badge>
      </div>

      {/* Templates Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {filteredTemplates.map((template) => (
          <UnifiedCard
            key={template.id}
            title={template.title}
            description={template.description}
            subjectLabel={template.category}
            difficultyLevel={template.isOnlineWritable ? "Online" : "Download Only"}
            topicTags={template.tags}
            duration="Self-paced"
            subject={template.category}
            userCount={template.downloads}
            onPreview={() => console.log(`Preview template: ${template.title}`)}
            onPrimaryAction={() => 
              template.isOnlineWritable 
                ? handleStartWriting(template.title)
                : handleDownload(template.title)
            }
            primaryActionLabel={template.isOnlineWritable ? "Start Writing" : "Download"}
            previewLabel="Preview"
            isHot={template.downloads > 3000}
            isPriority={template.isOnlineWritable}
          />
        ))}
      </div>

      {/* No Results */}
      {filteredTemplates.length === 0 && (
        <div className="text-center py-12">
          <FileText className="w-12 h-12 mx-auto mb-4 text-gray-400" />
          <p className="text-gray-600 mb-2">No templates found</p>
          <p className="text-sm text-gray-500">Try adjusting your search or filters</p>
          <Button 
            variant="outline" 
            onClick={() => {
              setSearchQuery("");
              setSelectedCategory("all");
              setSortBy("popular");
              setShowOnlineWritableOnly(false);
            }}
            className="mt-4"
          >
            Clear Filters
          </Button>
        </div>
      )}
    </div>
  );
}
